package org.example.product.service.impl;

import org.example.core.utils.R;
import org.example.product.dao.CategoryDao;
import org.example.product.entity.CategoryEntity;
import org.example.product.service.*;
import org.example.product.vo.CategoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author 小杰_cc
 * @version 1.0
 */
@Service("categoryService")
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private AttributeCategoryService attributeCategoryService;
    @Autowired
    private BrandCategoryService brandCategoryService;
    @Autowired
    @Lazy
    private SpuInfoService spuInfoService;

    // 获取分类树
    @Override
    public List<CategoryVo> tree() {
        // 获取全部分类数据
        List<CategoryVo> entities = categoryDao.getCategoryAll();
        // 递归查找子菜单
        List<CategoryVo> categoryVos = entities.stream().filter(category -> "0".equals(category.getPid().toString()))
                .peek(item -> {
                    item.setChildren(getChildren(item.getId(), entities));
                }).collect(Collectors.toList());
        return categoryVos;
    }

    // 查询单个分类信息
    @Override
    public CategoryEntity queryCategoryInfoById(Long id) {
        return categoryDao.getCategoryInfoById(id);
    }

    // 添加分类信息
    @Override
    public int saveCategoryInfo(CategoryEntity categoryEntity) {
        return categoryDao.addCategoryInfo(categoryEntity);
    }

    // 修改分类数据
    @Override
    public int editCategoryInfo(CategoryEntity categoryEntity) {
        return categoryDao.updateCategoryInfo(categoryEntity);
    }

    @Override
    @Transactional
    public R<?> deletes(List<Long> ids) {
        // 是否关联商品
        if (spuInfoService.isSpuByCategoryIds(ids)){
            return R.error("分类关联了商品不能删除");
        }
        // 删除分类关联的属性
        attributeCategoryService.deleteByCategoryIds(ids);
        // 删除关联的品牌
        brandCategoryService.deleteByCategoryIds(ids);
        // 删除分类
        return categoryDao.deletes(ids)>0? R.ok():R.error();
    }

    // 递归方法
    private List<CategoryVo> getChildren(Long pid, List<CategoryVo> entities) {
        List<CategoryVo> collect = entities.stream().filter(item -> pid.toString().equals(item.getPid().toString()))
                .peek(item -> item.setChildren(getChildren(item.getId(), entities))).collect(Collectors.toList());
        return collect;
    }
}